package com.solution.admin.message.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solution.admin.message.constants.MessageConstants.ReceiveType;
import com.solution.admin.message.entity.MessageEntity;
import com.solution.admin.message.service.MessageService;
import com.solution.admin.settings.service.SortService;
import com.solution.common.config.PublicConfig;
import com.solution.common.constants.PublicStatus.IS_DELETE;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.constants.PublicStatus.SysCode;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.BaseReturn;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;

/**
 * 消息管理web控制层
 * 
 * @author xu_cc
 * @date 2017-11-22 15:18:58
 */
@RequestMapping("/message")
@Controller
public class MessageController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(MessageController.class);

	@Autowired
	private MessageService messageService;

	@Autowired
	private SortService sortService;

	/**
	 * 跳转消息管理查询页面
	 * 
	 * @param Message
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-11-22 15:18:58
	 */
	@RequestMapping("/toListMessagePage")
	public String toListMessagePage(MessageEntity message, HttpServletRequest request) {
		return "message/message_list";
	}

	/**
	 * 分页查询消息管理列表
	 * 
	 * @param message
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-11-22 15:18:58
	 */
	@RequestMapping("/listMessagePage")
	@ResponseBody
	public JSONGrid listMessagePage(MessageEntity message, HttpServletRequest request) {
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("title", request.getParameter("title"));
			paramMap.put("messageType", request.getParameter("messageType"));
			paramMap.put("status", request.getParameter("status"));

			PageBean pageBean = messageService.listMessagePage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询消息管理失败", logger, e);
		}
		return new JSONGrid();
	}

	/**
	 * 跳转新增页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-11-22 15:18:58
	 */
	@RequestMapping("/toAddMessage")
	public String toAddMessage(HttpServletRequest request) {
		return "message/message_form";
	}

	/**
	 * 跳转编辑页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-11-22 15:18:58
	 */
	@RequestMapping("/toDetail")
	public String toDetail(HttpServletRequest request, Model model) {
		// 编辑操作
		try {
			long id = Long.valueOf(request.getParameter("id"));
			MessageEntity message = messageService.getMessageById(id);
			// 图文描述的图片地址替换 TEMPPATH换成路径
			if (StringUtil.isNotNull(message.getContent())) {
				String content = message.getContent().replaceAll("TEMPPATH", PublicConfig.IMG_ROOT_URL);
				String path = request.getContextPath();
				String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
				content = content.replaceAll("/ueditor", basePath + "ueditor");
				message.setContent(content);
			}
			model.addAttribute("message", message);
		} catch (Exception e) {
			e.printStackTrace();
			return toListMessagePage(null, request);
		}
		return "message/message_detail";
	}

	/**
	 * 跳转编辑页面
	 * 
	 * @return string 跳转页面路径
	 * @author xu_cc
	 * @date 2017-11-22 15:18:58
	 */
	@RequestMapping("/toUpdateMessage")
	public String toUpdateMessage(HttpServletRequest request, Model model) {
		// 编辑操作
		try {
			long id = Long.valueOf(request.getParameter("id"));
			MessageEntity message = messageService.getMessageById(id);
			// 图文描述的图片地址替换 TEMPPATH换成路径
			if (StringUtil.isNotNull(message.getContent())) {
				String content = message.getContent().replaceAll("TEMPPATH", PublicConfig.IMG_ROOT_URL);
				message.setContent(content);
			}
			model.addAttribute("message", message);
		} catch (Exception e) {
			e.printStackTrace();
			return toListMessagePage(null, request);
		}
		return "message/message_form";
	}

	/**
	 * 新增或保存消息管理
	 * 
	 * @param request
	 *            请求对象
	 * @param messageEntity
	 *            消息管理实体
	 * @return
	 * @author xu_cc
	 * @date 2017-11-22 15:18:58
	 */
	@RequestMapping("/saveMessage")
	@ResponseBody
	public BaseReturn saveMessage(HttpServletRequest request, MessageEntity message) {
		BaseReturn result = new BaseReturn();
		try {
			String id = request.getParameter("id");
			message.setModifier(getUserName());
			if (StringUtil.isNotEmpty(id)) {
				messageService.updateMessage(message);
			} else {
				// 发送给所有人
				message.setReceiveType(ReceiveType.TYPE_ALL);
				message.setCreater(getUserName());
				message.setIsDelete(IS_DELETE.NORMAL.getId());
				message.setStatus(STATUS.ENABLED.getId());
				// 新建消息在最上
				int sortNo = sortService.getFirstSortNo("eb_message");
				message.setSortNo(sortNo);
				messageService.saveMessage(message);
			}
			result.setCode(com.solution.common.constants.PublicStatus.SysCode.SUCCESS);
			result.setMsg("消息管理保存成功！");
		} catch (Exception e) {
			result.setCode(com.solution.common.constants.PublicStatus.SysCode.ERROR);
			result.setMsg("消息管理保存异常！");
		}
		return result;
	}

	/**
	 * 修改状态
	 * 
	 * @param request
	 * @param id
	 * @param status
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年10月11日 下午8:23:02
	 */
	@RequestMapping("/updateStatus")
	@ResponseBody
	public BaseReturn updateStatus(HttpServletRequest request, Long id, String status) {
		BaseReturn result = new BaseReturn();
		try {
			MessageEntity message = new MessageEntity();
			message.setId(id);
			message.setStatus(Integer.parseInt(status));
			message.setModifier(getUserName());
			int rows = messageService.updateMessage(message);
			if (rows > 0) {
				result.setCode(SysCode.SUCCESS);
				result.setMsg("状态修改成功！");
			} else {
				result.setCode(SysCode.FAILED);
				result.setMsg("状态修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("状态更新异常！");
		}
		return result;
	}

	/**
	 * 发送订单消息
	 * 
	 * @param request
	 * @param orderCode
	 * @param orderStatus
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月27日 上午11:01:13
	 */
	@RequestMapping("/doSendOrder")
	@ResponseBody
	public BaseReturn doSendOrderMessage(HttpServletRequest request, String orderCode, String orderStatus) {
		BaseReturn result = new BaseReturn();
		try {
			long messageId = messageService.doSendOrderToUser(orderCode, orderStatus);
			result.setCode(SysCode.SUCCESS);
			result.setMsg("消息发送成功！" + messageId);
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("状态更新异常！");
		}
		return result;
	}

}
